package com.example.my_isc_nirscan.utils;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;

public class HttpUtils {
    private static HttpUtils instance;
    private OkHttpClient client;

    private HttpUtils() {
        client = new OkHttpClient();
    }

    public static HttpUtils getInstance() {
        if (instance == null) {
            synchronized (HttpUtils.class) {
                if (instance == null) {
                    instance = new HttpUtils();
                }
            }
        }
        return instance;
    }

    public void get(String url, HttpCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        executeRequest(request, callback);
    }

    public void post(String url, String jsonData, HttpCallback callback) {
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                jsonData
        );

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        executeRequest(request, callback);
    }

    private void executeRequest(Request request, final HttpCallback callback) {
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (callback != null) {
                    callback.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (callback != null) {
                    if (response.isSuccessful()) {
                        String responseData = response.body().string();
                        callback.onSuccess(responseData);
                    } else {
                        callback.onFailure(new IOException("请求失败: " + response.code()));
                    }
                }
            }
        });
    }

    public interface HttpCallback {
        void onSuccess(String response);
        void onFailure(Exception e);
    }
}
